from django.contrib import admin
from django.db import connection
from controlpanel.models import Object, ObjectField, ObjectForm, ObjectList
import logging

logger = logging.getLogger(__name__)

class FieldsInline(admin.TabularInline):
    model = ObjectField
    extra = 1
    
class FormsInline(admin.StackedInline):
    model = ObjectForm
    extra = 0
    
class ObjectAdmin(admin.ModelAdmin):
    inlines = [FieldsInline, FormsInline]
    
    def save_formset(self, request, form, formset, change):
        """
        Overwrite save_formset. Will create tables for all formsets.
        """
        instances = formset.save(commit=False)
        for instance in instances:
            #instance.user = request.user
            instance.save()
            logger.debug(instance)
        formset.save_m2m()
    
    def save_model(self, request, obj, form, change):
        """
        Overwrite save_model. Will create a table for records
        for the new object.
        """
        logger.debug(obj)
        
        # Create the table for the object records
        cursor = connection.cursor()
        # TODO: Make sure we can roll bak if someting goes wrong
        #cursor.execute("CREATE TABLE `test` (`id` int(11) NOT NULL auto_increment, `name` VARCHAR(200) NOT NULL, primary key (`id`))")
        
        # Save the meta class
        obj.save()

admin.site.register(Object, ObjectAdmin)
#admin.site.register(ObjectField)
#admin.site.register(ObjectForm)
#admin.site.register(ObjectList)